/*
* @Author: Youjiang Xie
* @Date:   2019-11-03 10:14:37
* @Last Modified by:   YouJiang Xie
* @Last Modified time: 2019-11-03 16:59:08
* @E-mail:xie_youjiang@163.com
*/
var mapControl = {
    init: function() {
        this.onLoad();
        this.bindEvent();
    },

    onLoad: function() {

        this.loadMap();
    },

    bindEvent: function() {
        var _this = this;

        $("#metermap").click(function() {
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='metermap']").attr('checked', 'checked');
                _this.loadMeterMonitor();
            } else {
                $("input[name='metermap']").attr('checked', false);
                var params = {};
                params['flag'] = "metermap";
                _this.removeMarkers(params);
            }
        });

        $("#wellcover").click(function() {
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='wellcover']").attr('checked', 'checked');
                //_this.loadWellCover();
            } else {
                $("input[name='wellcover']").attr('checked', false);
                var params = {};
                params['flag'] = "wellcover";
                //_this.removeMarkers();
            }
        });

        $("#waterquality").click(function() {
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='waterquality']").attr('checked', 'checked');
                _this.loadWaterQuality();
            } else {
                $("input[name='waterquality']").attr('checked', false);
                var markers = map.getOverlays();
                for (var index = 0; index < markers.length; index++) {
                    if (markers[index].toString() === "[object Marker]") {
                        if (markers[index].getTitle() === "中国航油集团北方储运有限公司") {
                            map.removeOverlay(markers[index]);
                        }
                    }
                }
            }
        });

        $("#areaone").click(function() {
            var params = {};
            params['flag'] = "areaone";
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='areaone']").attr('checked', 'checked');
                _this.showAreaMeter(params);
            } else {
                $("input[name='areaone']").attr('checked', false);
                _this.removeMarkers(params);
            }
        });

        $("#areatwo").click(function() {
            var params = {};
            params['flag'] = "areatwo";
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='areatwo']").attr('checked', 'checked');
                _this.showAreaMeter(params);
            } else {
                $("input[name='areatwo']").attr('checked', false);

                _this.removeMarkers(params);
            }
        });

        $("#areathree").click(function() {
            var params = {};
            params['flag'] = "areathree";
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='areathree']").attr('checked', 'checked');
                _this.showAreaMeter(params);
            } else {
                $("input[name='areathree']").attr('checked', false);

                _this.removeMarkers(params);
            }
        });

        $("#areafour").click(function() {
            var params = {};
            params['flag'] = "areafour";
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='areafour']").attr('checked', 'checked');
                _this.showAreaMeter(params);
            } else {
                $("input[name='areafour']").attr('checked', false);
                _this.removeMarkers(params);
            }
        });

        $("#areafive").click(function() {
            var params = {};
            params['flag'] = "areafive";
            if (!($(this).attr('checked') == 'checked')) {
                $("input[name='areafive']").attr('checked', 'checked');
                _this.showAreaMeter(params);
            } else {
                $("input[name='areafive']").attr('checked', false);

                _this.removeMarkers(params);
            }
        });

        $('#devLoseWaterTable tbody').on('click', 'tr', function () {
            var data = $('#devLoseWaterTable').DataTable().row(this).data();
            _this.loadLocation(data);
        });

    },

    loadLocation: function (data) {
        var markers = map.getOverlays();
        for (var index = 0; index < markers.length; index++) {
            if (markers[index].toString() === "[object Marker]") {
                if (markers[index].getTitle() == data.devSn) {
                    var point = markers[index].getPosition();
                    var pts = wgs2bd(Number(point.lat), Number(point.lng));
                    var center = new BMap.Point(pts[1], pts[0]);
                    map.centerAndZoom(center, 14);

                    markers[index].setAnimation(BMAP_ANIMATION_BOUNCE);//跳动的动画
                } else {
                    markers[index].setAnimation(null);
                }
            }
        }
    },

    loadMap: function() {
        var pts = wgs2bd(38.962775, 117.7929972);
        var center = new BMap.Point(pts[1], pts[0]);
        //var center = new BMap.Point(117.7329972 + 0.01115, 38.972775 + 0.007);
        map = new BMap.Map("map", {
            enableMapClick: false
        });
        map.centerAndZoom(center, 14);
        map.enableDragging();
        map.enableInertialDragging();
        map.enableScrollWheelZoom();
        map.enableDoubleClickZoom();
        map.enableKeyboard();
        map.enableContinuousZoom();
        var ctrl_type = new BMap.MapTypeControl({
            mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP,
                BMAP_HYBRID_MAP
            ],
            anchor: BMAP_ANCHOR_TOP_LEFT,
            offset: new BMap.Size(20, 20)
        });
        map.addControl(ctrl_type);
        this.loadPipe();
        this.loadMeterMonitor();
    },

    // 加载管网信息
    loadPipe: function() {
        var _this = this;
        $.getJSON("view/assets/js/pipeline/DN150.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 1);
            }
        });
        $.getJSON("view/assets/js/pipeline/DN200.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 2);
            }
        });
        $.getJSON("view/assets/js/pipeline/DN300.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 3);
            }
        });
        $.getJSON("view/assets/js/pipeline/DN350.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 3);
            }
        });
        $.getJSON("view/assets/js/pipeline/DN400.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 3);
            }
        });
        $.getJSON("view/assets/js/pipeline/DN500.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 4);
            }
        });
        $.getJSON("view/assets/js/pipeline/DN600.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 5);
            }
        });
        $.getJSON("view/assets/js/pipeline/YDN150.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 4);
            }
        });
        $.getJSON("view/assets/js/pipeline/YDN600.json", "", function(data) {
            if (data != null && data.features != null) {
                _this.drawLines(data.features, "#8bb209", 5);
            }
        });

        // $.getJSON("view/assets/js/watermeter.json", "", function(data){
        // if(data != null && data.features != null) {
        // for (var index = 0; index < data.features.length; index ++){
        // var pts = wgs2bd(data.features[index].geometry.y,
        // data.features[index].geometry.x);;
        // var point = new BMap.Point(pts[1], pts[0]);
        // // var
        // pointLong=Number(data.features[index].geometry.x)+Number(0.01285);
        // // var
        // pointLat=Number(data.features[index].geometry.y)+Number(0.007);
        // //var point = new BMap.Point(pointLong,pointLat);
        // var icon = new BMap.Icon("view/assets/images/red_watermeter.png", new
        // BMap.Size(32, 32));
        // var marker = new BMap.Marker(point, { icon : icon });

        // var label = new BMap.Label("你好");
        // marker.setLabel(label);
        // map.addOverlay(marker);

        // }

        // }
        // });
    },

    drawLines: function(features, colors, width) {
        if (features != null && features.length > 0) {
            for (var i = 0; i < features.length; i++) {
                var feature = features[i];
                if (feature != null && feature.geometry != null &&
                    feature.geometry.paths != null) {
                    var points = new Array();
                    for (var j = 0; j < feature.geometry.paths.length; j++) {
                        var data = feature.geometry.paths[j];
                        for (var m = 0; m < data.length; m++) {
                            // 管线偏移量
                            var pts = wgs2bd(data[m][1], data[m][0]);;
                            var point = new BMap.Point(pts[1], pts[0]);
                            points.push(point);
                        }
                    }
                    this.drawLine(points, colors, width);
                }
            }
        }
    },

    drawLine: function(points, colors, width) {
        var lines = new BMap.Polyline(points, {
            strokeColor: colors,
            strokeWeight: width,
            strokeOpacity: 1
        });
        map.addOverlay(lines);
    },

    loadMeterMonitor: function() {
        var _this = this;
        $.getJSON("watermeter/getMeterInfo", "", function(res) {
            if (res != null && res.data != null) {
                $.each(res.data, function(i, monitor) {
                    // 水表偏移量
                    var pts = wgs2bd(Number(monitor.latitude), Number(monitor.longitude));
                    var point = new BMap.Point(pts[1], pts[0]);

                    if (monitor.deviceSn === '18092800170030') {
                        var icon = new BMap.Icon("view/assets/images/total_meter.png", new BMap.Size(32, 32));
                    } else if ( monitor.deviceSn === '18092800170002' ||
                                monitor.deviceSn === '18092800170015' ||
                                monitor.deviceSn === '18092800170170' ||
                                monitor.deviceSn === '18092800170181' ||
                                monitor.deviceSn === '18092800170177') {
                                icon = new BMap.Icon("view/assets/images/ssjk/kaohebiao.png", new BMap.Size(32, 32));
                                point = new BMap.Point(Number(monitor.longitude), Number(monitor.latitude));
                                console.log(icon);
                    } else {
                        if (monitor.meterarea === 1) {
                            icon = new BMap.Icon("view/assets/images/ssjk/shuibiao1.png", new BMap.Size(32, 32));
                        }else if (monitor.meterarea === 2) {
                            icon = new BMap.Icon("view/assets/images/ssjk/shuibiao2.png", new BMap.Size(32, 32));
                        }else if (monitor.meterarea === 3) {
                            icon = new BMap.Icon("view/assets/images/ssjk/shuibiao3.png", new BMap.Size(32, 32));
                        }else if (monitor.meterarea === 4) {
                            icon = new BMap.Icon("view/assets/images/ssjk/shuibiao4.png", new BMap.Size(32, 32));
                        }else if (monitor.meterarea === 5) {
                            icon = new BMap.Icon("view/assets/images/ssjk/shuibiao5.png", new BMap.Size(32, 32));
                        }

                    }

                    var marker = new BMap.Marker(point, { icon: icon });
                    //var label = new BMap.Label(monitor.name);
                    marker.setTitle(monitor.deviceSn);
                    map.addOverlay(marker);

                    marker.addEventListener("click", function() {
                        var data = {};
                        data['deviceName'] = monitor.deviceName;
                        data['deviceSn'] = monitor.deviceSn;
                        data['state'] = monitor.state;
                        data['longitude'] = monitor.longitude;
                        data['latitude'] = monitor.latitude;

                        $.getJSON("watermeter/getLastMeterDataBySn", {
                            "devSn": monitor.deviceSn
                        }, function(res) {
                            data['ma420'] = res.ma420;
                            data['totalNum'] = res.totalNum;
                            data['updateTime'] = res.updateTime;
                            var content = _this.getWindowInfo(data);
                            _this.openInfo(content, point);
                        });

                    });
                  
                });
            }
        });
    },

    loadWaterQuality: function() {
        var _this = this;

        $.getJSON("view/assets/js/Monitor_sz.json", "", function(data) {
            if (data != null && data.points != null) {
                $.each(data.points, function(i, monitor) {

                    var pts = wgs2bd(Number(monitor.lat), Number(monitor.lon));
                    var point = new BMap.Point(pts[1], pts[0]);
                    var icon = new BMap.Icon("view/assets/images/ssjk/shuizhidian.png", new BMap.Size(30, 30));
                    var marker = new BMap.Marker(point, { icon: icon });
                    marker.setTitle(monitor.name);
                    map.addOverlay(marker);
                    marker.addEventListener("click", function() {
                        //_this.showInfo(this, point);
                    });
                });
            }
        })
    },

    removeMarkers: function(params) {
        var markers = map.getOverlays();
        $.getJSON("watermeter/getMapLevelData", params, function(res) {
            if (res.success === true) {
                if (res.data != null) {
                    $.each(res.data, function(items, item) {
                        for (var index = 0; index < markers.length; index++) {
                            if (markers[index].toString() === "[object Marker]") {

                                if (markers[index].getTitle() == item.deviceSn) {
                                    map.removeOverlay(markers[index]);
                                    break;
                                }
                            }
                        }
                    })
                }
            } else {
                alert(res.msg);
            }


        })

    },

    showAreaMeter: function(params) {
        var _this = this;
        this.removeMarkers(params);
        $.getJSON("watermeter/getMapLevelData", params, function(res) {
            if (res.success === true && res.data != null) {
                $.each(res.data, function(i, monitor) {

                    var pts = wgs2bd(Number(monitor.latitude), Number(monitor.longitude));
                    var point = new BMap.Point(pts[1], pts[0]);

                    if (params.flag === "areaone") {
                        var icon = new BMap.Icon("view/assets/images/ssjk/shuibiao1.png", new BMap.Size(32, 32));
                    } else if (params.flag === "areatwo") {
                        icon = new BMap.Icon("view/assets/images/ssjk/shuibiao2.png", new BMap.Size(32, 32));
                    } else if (params.flag === "areathree") {
                        icon = new BMap.Icon("view/assets/images/ssjk/shuibiao3.png", new BMap.Size(32, 32));
                    } else if (params.flag === "areafour") {
                        icon = new BMap.Icon("view/assets/images/ssjk/shuibiao4.png", new BMap.Size(32, 32));
                    } else if (params.flag === "areafive") {
                        icon = new BMap.Icon("view/assets/images/ssjk/shuibiao5.png", new BMap.Size(32, 32));
                    }
                    console.log(point);
                    var marker = new BMap.Marker(point, { icon: icon });
                    marker.setTitle(monitor.deviceSn);
                    map.addOverlay(marker);
                    marker.addEventListener("click", function() {
                        var data = {};
                        data['deviceName'] = monitor.deviceName;
                        data['deviceSn'] = monitor.deviceSn;
                        data['state'] = monitor.state;
                        data['longitude'] = monitor.longitude;
                        data['latitude'] = monitor.latitude;

                        $.getJSON("watermeter/getLastMeterDataBySn", {
                            "devSn": monitor.deviceSn
                        }, function(res) {
                            data['ma420'] = res.ma420;
                            data['totalNum'] = res.totalNum;
                            data['updateTime'] = res.updateTime;
                            var content = _this.getWindowInfo(data);
                            _this.openInfo(content, point);
                        });
                    });
                });
            } else {
                alert(res.msg);
            }

        })
    },
    fopen: function() {
        $.openHaiwiModal("modalDiv");
    },

    fclose: function() {
        $.closeHaiwiModal("modalDiv");
    },

    openInfo: function(content, point) {
        var infoWindow = new BMap.InfoWindow(content);
        map.openInfoWindow(infoWindow, point);
        // map.centerAndZoom(point, 18);
    },

    getWindowInfo: function(data) {
        var state = "";
        if (data.state == 1) {
            state = "正常";
        } else {
            state = "异常";
        }
        var ma420 = "";
        if (data.ma420 != undefined) {
            ma420 = data.ma420;
        }
        var vContent = "<div class=\"container\">" +
            "        <div class=\"title\">" +
            "            <label><strong>" + data.deviceName + "</strong></label>" +
            /*"             <a onclick=\"window.mapControl.getHistoryData(\'" + data.deviceSn + "\');\" data-toggle=\"modal\">详情>></a>" +*/
            "        </div>" +
            /*"        <div class=\"img_container\">" +
            "            <img src=\"view/assets/images/watermeterlocation/meter.jpg\" />" +
            "        </div>" +*/
            "        <div class=\"line\"></div>" +
            "            <div class=\"table_contianer\">" +
            "                <table class=\"table_context\">" +
            "                    <tr>" +
            "                        <td>状态：</td>" +
            "                        <td class=\"table_value\">" + state + "</td>" +
            "                    </tr>" +
            "                    <tr>" +
            "                        <td>经度：</td>" +
            "                        <td class=\"table_value\">" + data.longitude + "</td>" +
            "                    </tr>" +
            "                    <tr>" +
            "                        <td>纬度：</td>" +
            "                        <td class=\"table_value\">" + data.latitude + "</td>" +
            "                    </tr>" +
            "                    <tr>" +
            "                        <td>压力：</td>" +
            "                        <td class=\"table_value\">" + ma420 + "</td>" +
            "                    </tr>" +
            "                    <tr>" +
            "                        <td>流量：</td>" +
            "                        <td class=\"table_value\">" + data.totalNum + "</td>" +
            "                    </tr>" +
            "                    <tr>" +
            "                        <td>更新时间：</td>" +
            "                        <td class=\"table_value\">" + data.updateTime + "</td>" +
            "                    </tr>" +
            "                </table>" +
            "            </div>" +
            "        </div>";

        return vContent;
    },

    getHistoryData: function(deviceSn) {
        var _this = this;
        $.openHaiwiModal("modalDiv");
        $("#meterHistory").html("");
        this.createPages("pages", 1);
        if (deviceSn == "") {
            alert("请先点击要查看的设备！");
            return;
        }
        var params = {};
        params['deviceSn'] = deviceSn;

        $.ajax({
            type: 'post',
            url: "watermeter/getWaterMeterHistoryData",
            data: params,
            dataType: 'json',
            success: function(res) {

                if (res.success === true) {
                    var strTr = "";
                    var index = 0;
                    $.each(res.data, function(i, item) {
                        index = i + 1;
                        strTr = strTr + "<tr>" + "<td>" + index + "</td>" +
                            "<td>" + item.deviceName + "</td>" + "<td>" +
                            item.deviceSn + "</td>" + "<td>" +
                            item.updateTime + "</td>" + "<td>" +
                            item.totalNum + "</td>" + "<td>" + item.ma420 +
                            "</td>" + "</tr>";
                    });
                    $("#meterHistory").html(strTr);

                    _this.createPages("pages", res.size);
                } else {
                    alert(res.msg);
                }
            },
            error: function(xhr, status, errorThrow) {
                // console.log(errorThorw);
            }
        })
    },

    getCurPageData: function(pageNumber) {
        var params = {};
        params['pageNumber'] = pageNumber;
        params['type'] = "mapLevelDetails";
        $.ajax({
            type: 'post',
            url: "watermeter/getCurPageData",
            data: params,
            dataType: 'json',
            success: function(res) {
                if (res.success === true) {
                    console.log(res.data, params);
                    var strTr = "";
                    var index = 0;
                    $.each(res.data, function(i, item) {
                        index = i + 1 + (pageNumber - 1) * 15;
                        strTr = strTr + "<tr>" + "<td>" + index + "</td>" +
                            "<td>" + item.deviceName + "</td>" + "<td>" +
                            item.deviceSn + "</td>" + "<td>" +
                            item.updateTime + "</td>" + "<td>" +
                            item.totalNum + "</td>" + "<td>" + item.ma420 +
                            "</td>" + "</tr>";
                    });
                    $("#meterHistory").html(strTr);
                } else {
                    alert(res.msg);
                }
            },
            error: function(xhr, status, errorThrow) {
                console.log(status);
                // console.log(errorThorw);
            }
        })
    },

    createPages: function(name, pageCount) {
        var _this = this;
        var container = $('#pagination-' + name);
        var sources = function() {
            var result = [];

            for (var i = 1; i < pageCount; i++) {
                result.push(i);
            }

            return result;
        }();
        var options = {
            dataSource: sources,
            pageSize: 15,
            className: 'paginationjs-theme-blue',
            callback: function(response, pagination) {
                _this.getCurPageData(pagination.pageNumber);
                var dataHtml = '<ul>';

                $.each(response, function(index, item) {
                    dataHtml += '<li>' + item + '</li>';
                });

                dataHtml += '</ul>';

                container.prev().html(dataHtml);
            }
        };

        // $.pagination(container, options);

        container.addHook('beforeInit', function() {});
        container.pagination(options);

        container.addHook('beforePageOnClick', function() {
            // return false
        });

        return container;
    }
}



$(function() {
    mapControl.init();
})